// SPDX-License-Identifier: GPL-2.0
/*
 * LD_MIPI driver
 *
 * Copyright (C) 2017 Fuzhou Rockchip Electronics Co., Ltd.
 *
 * V0.0X01.0X01 add poweron function.
 */

#include <linux/clk.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/gpio/consumer.h>
#include <linux/i2c.h>
#include <linux/module.h>
#include <linux/pm_runtime.h>
#include <linux/regulator/consumer.h>
#include <linux/sysfs.h>
#include <linux/slab.h>
#include <linux/version.h>
#include <linux/rk-camera-module.h>
#include <media/media-entity.h>
#include <media/v4l2-async.h>
#include <media/v4l2-ctrls.h>
#include <media/v4l2-subdev.h>
#include <linux/pinctrl/consumer.h>

//MEDIA_BUS_FMT_UYVY8_2X8;	//MEDIA_BUS_FMT_YUYV8_2X8
#define LD_MIPI_FMT	(MEDIA_BUS_FMT_UYVY8_2X8)

#define DRIVER_VERSION			KERNEL_VERSION(0, 0x01, 0x01)

#ifndef V4L2_CID_DIGITAL_GAIN
#define V4L2_CID_DIGITAL_GAIN		V4L2_CID_GAIN
#endif

#if 1
#define LD_MIPI_LINK_FREQ_300MHZ	300000000
/* pixel rate = link frequency * 2 * lanes / BITS_PER_SAMPLE */
#define LD_MIPI_PIXEL_RATE		(LD_MIPI_LINK_FREQ_300MHZ*2*2/8)
#define LD_MIPI_XVCLK_FREQ		24000000

#else

#define LD_MIPI_LINK_FREQ_300MHZ	300000000
/* pixel rate = link frequency * 2 * lanes / BITS_PER_SAMPLE */
#define LD_MIPI_PIXEL_RATE		(LD_MIPI_LINK_FREQ_300MHZ * 2 * 2 / 10)
#define LD_MIPI_XVCLK_FREQ		24000000

#endif

#define CHIP_ID				0x00d850
#define LD_MIPI_REG_CHIP_ID		0x300a

#define LD_MIPI_REG_CTRL_MODE		0x0100
#define LD_MIPI_MODE_SW_STANDBY		0x0
#define LD_MIPI_MODE_STREAMING		BIT(0)

#define LD_MIPI_REG_EXPOSURE		0x3500
#define	LD_MIPI_EXPOSURE_MIN		4
#define	LD_MIPI_EXPOSURE_STEP		1
#define LD_MIPI_VTS_MAX			0x7fff

#define LD_MIPI_REG_GAIN_H		0x350a
#define LD_MIPI_REG_GAIN_L		0x350b
#define LD_MIPI_GAIN_H_MASK		0x07
#define LD_MIPI_GAIN_H_SHIFT		8
#define LD_MIPI_GAIN_L_MASK		0xff
#define LD_MIPI_GAIN_MIN		0x10
#define LD_MIPI_GAIN_MAX		0xf8
#define LD_MIPI_GAIN_STEP		1
#define LD_MIPI_GAIN_DEFAULT		0x10

#define LD_MIPI_REG_TEST_PATTERN	0x5e00
#define	LD_MIPI_TEST_PATTERN_ENABLE	0x80
#define	LD_MIPI_TEST_PATTERN_DISABLE	0x0

#define LD_MIPI_REG_VTS			0x380e

#define REG_NULL			0xFFFF

#define LD_MIPI_REG_VALUE_08BIT		1
#define LD_MIPI_REG_VALUE_16BIT		2
#define LD_MIPI_REG_VALUE_24BIT		3

#define LD_MIPI_LANES			4
#define LD_MIPI_BITS_PER_SAMPLE		10

#define LD_MIPI_CHIP_REVISION_REG	0x302A
#define LD_MIPI_R1A			0xb1
#define LD_MIPI_R2A			0xb2

#define OF_CAMERA_PINCTRL_STATE_DEFAULT	"rockchip,camera_default"
#define OF_CAMERA_PINCTRL_STATE_SLEEP	"rockchip,camera_sleep"

#define LD_MIPI_NAME			"LD_MIPI"

static const char * const LD_MIPI_supply_names[] = {
	"avdd",		/* Analog power */
	"dovdd",	/* Digital I/O power */
	"dvdd",		/* Digital core power */
};

#define LD_MIPI_NUM_SUPPLIES ARRAY_SIZE(LD_MIPI_supply_names)

struct regval {
	u16 addr;
	u8 val;
};

struct LD_MIPI_mode {
	u32 width;
	u32 height;
	struct v4l2_fract max_fps;
	u32 hts_def;
	u32 vts_def;
	u32 exp_def;
	const struct regval *reg_list;
};

struct LD_MIPI {
	struct i2c_client	*client;
	struct clk		*xvclk;
	struct gpio_desc	*pwr_gpio;
	struct gpio_desc	*reset_gpio;
	struct gpio_desc	*pwdn_gpio;
	struct regulator_bulk_data supplies[LD_MIPI_NUM_SUPPLIES];

	struct pinctrl		*pinctrl;
	struct pinctrl_state	*pins_default;
	struct pinctrl_state	*pins_sleep;

	struct v4l2_subdev	subdev;
	struct media_pad	pad;
	struct v4l2_ctrl_handler ctrl_handler;
	struct v4l2_ctrl	*exposure;
	struct v4l2_ctrl	*anal_gain;
	struct v4l2_ctrl	*digi_gain;
	struct v4l2_ctrl	*hblank;
	struct v4l2_ctrl	*vblank;
	struct v4l2_ctrl	*test_pattern;
	struct mutex		mutex;
	bool			streaming;
	bool			power_on;
	const struct LD_MIPI_mode *cur_mode;
	u32			module_index;
	const char		*module_facing;
	const char		*module_name;
	const char		*len_name;
};

#define to_LD_MIPI(sd) container_of(sd, struct LD_MIPI, subdev)


static const struct LD_MIPI_mode supported_modes[] = {
	{
		.width = 1920,
		.height = 1080,
		.max_fps = {
			.numerator = 10000,
			.denominator = 300000,
		},
		.exp_def = 0x0600,
		.hts_def = 0x12c0,
		.vts_def = 0x0680,
	},
};

static const s64 link_freq_menu_items[] = {
	LD_MIPI_LINK_FREQ_300MHZ
};

static const char * const LD_MIPI_test_pattern_menu[] = {
	"Disabled",
	"Vertical Color Bar Type 1",
	"Vertical Color Bar Type 2",
	"Vertical Color Bar Type 3",
	"Vertical Color Bar Type 4"
};




static const struct LD_MIPI_mode *
LD_MIPI_find_best_fit(struct v4l2_subdev_format *fmt)
{
	return &supported_modes[0];
}

static int LD_MIPI_set_fmt(struct v4l2_subdev *sd,
			   struct v4l2_subdev_pad_config *cfg,
			  struct v4l2_subdev_format *fmt)
{
	struct LD_MIPI *LD_MIPI = to_LD_MIPI(sd);
	const struct LD_MIPI_mode *mode;
	s64 h_blank, vblank_def;

	mutex_lock(&LD_MIPI->mutex);

	mode = LD_MIPI_find_best_fit(fmt);
	fmt->format.code = LD_MIPI_FMT;
	fmt->format.width = mode->width;
	fmt->format.height = mode->height;
	fmt->format.field = V4L2_FIELD_NONE;
	if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) {
#ifdef CONFIG_VIDEO_V4L2_SUBDEV_API
		*v4l2_subdev_get_try_format(sd, cfg, fmt->pad) = fmt->format;
#else
		mutex_unlock(&LD_MIPI->mutex);
		return -ENOTTY;
#endif
	} else {
		LD_MIPI->cur_mode = mode;
		h_blank = mode->hts_def - mode->width;
		__v4l2_ctrl_modify_range(LD_MIPI->hblank, h_blank,
					 h_blank, 1, h_blank);
		vblank_def = mode->vts_def - mode->height;
		__v4l2_ctrl_modify_range(LD_MIPI->vblank, vblank_def,
					 LD_MIPI_VTS_MAX - mode->height,
					 1, vblank_def);
	}

	mutex_unlock(&LD_MIPI->mutex);

	return 0;
}

static int LD_MIPI_get_fmt(struct v4l2_subdev *sd,
			   struct v4l2_subdev_pad_config *cfg,
			   struct v4l2_subdev_format *fmt)
{
	struct LD_MIPI *LD_MIPI = to_LD_MIPI(sd);
	const struct LD_MIPI_mode *mode = LD_MIPI->cur_mode;

	mutex_lock(&LD_MIPI->mutex);
	if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) {
#ifdef CONFIG_VIDEO_V4L2_SUBDEV_API
		fmt->format = *v4l2_subdev_get_try_format(sd, cfg, fmt->pad);
#else
		mutex_unlock(&LD_MIPI->mutex);
		return -ENOTTY;
#endif
	} else {
		fmt->format.width = mode->width;
		fmt->format.height = mode->height;
		fmt->format.code = LD_MIPI_FMT;
		fmt->format.field = V4L2_FIELD_NONE;
	}
	mutex_unlock(&LD_MIPI->mutex);

	return 0;
}

static int LD_MIPI_enum_mbus_code(struct v4l2_subdev *sd,
				  struct v4l2_subdev_pad_config *cfg,
				  struct v4l2_subdev_mbus_code_enum *code)
{
	if (code->index != 0)
		return -EINVAL;
	code->code = LD_MIPI_FMT;

	return 0;
}

static int LD_MIPI_enum_frame_sizes(struct v4l2_subdev *sd,
				    struct v4l2_subdev_pad_config *cfg,
				   struct v4l2_subdev_frame_size_enum *fse)
{
	if (fse->index >= ARRAY_SIZE(supported_modes))
		return -EINVAL;

	if (fse->code != LD_MIPI_FMT)
		return -EINVAL;

	fse->min_width  = supported_modes[fse->index].width;
	fse->max_width  = supported_modes[fse->index].width;
	fse->max_height = supported_modes[fse->index].height;
	fse->min_height = supported_modes[fse->index].height;

	return 0;
}

static int LD_MIPI_enable_test_pattern(struct LD_MIPI *LD_MIPI, u32 pattern)
{
	return 0;
}

static int LD_MIPI_g_frame_interval(struct v4l2_subdev *sd,
				    struct v4l2_subdev_frame_interval *fi)
{
	struct LD_MIPI *LD_MIPI = to_LD_MIPI(sd);
	const struct LD_MIPI_mode *mode = LD_MIPI->cur_mode;

	mutex_lock(&LD_MIPI->mutex);
	fi->interval = mode->max_fps;
	mutex_unlock(&LD_MIPI->mutex);

	return 0;
}

static void LD_MIPI_get_module_inf(struct LD_MIPI *LD_MIPI,
				   struct rkmodule_inf *inf)
{
	memset(inf, 0, sizeof(*inf));
	strlcpy(inf->base.sensor, LD_MIPI_NAME, sizeof(inf->base.sensor));
	strlcpy(inf->base.module, LD_MIPI->module_name,
		sizeof(inf->base.module));
	strlcpy(inf->base.lens, LD_MIPI->len_name, sizeof(inf->base.lens));
}

static long LD_MIPI_ioctl(struct v4l2_subdev *sd, unsigned int cmd, void *arg)
{
	struct LD_MIPI *LD_MIPI = to_LD_MIPI(sd);
	long ret = 0;

	switch (cmd) {
	case RKMODULE_GET_MODULE_INFO:
		LD_MIPI_get_module_inf(LD_MIPI, (struct rkmodule_inf *)arg);
		break;
	case RKMODULE_SET_QUICK_STREAM:
		break;
	default:
		ret = -ENOIOCTLCMD;
		break;
	}

	return ret;
}

#ifdef CONFIG_COMPAT
static long LD_MIPI_compat_ioctl32(struct v4l2_subdev *sd,
				   unsigned int cmd, unsigned long arg)
{
	void __user *up = compat_ptr(arg);
	struct rkmodule_inf *inf;
	struct rkmodule_awb_cfg *cfg;
	long ret;

	switch (cmd) {
	case RKMODULE_GET_MODULE_INFO:
		inf = kzalloc(sizeof(*inf), GFP_KERNEL);
		if (!inf) {
			ret = -ENOMEM;
			return ret;
		}

		ret = LD_MIPI_ioctl(sd, cmd, inf);
		if (!ret)
			ret = copy_to_user(up, inf, sizeof(*inf));
		kfree(inf);
		break;
	case RKMODULE_AWB_CFG:
		cfg = kzalloc(sizeof(*cfg), GFP_KERNEL);
		if (!cfg) {
			ret = -ENOMEM;
			return ret;
		}

		ret = copy_from_user(cfg, up, sizeof(*cfg));
		if (!ret)
			ret = LD_MIPI_ioctl(sd, cmd, cfg);
		kfree(cfg);
	case RKMODULE_SET_QUICK_STREAM:
		break;
		break;
	default:
		ret = -ENOIOCTLCMD;
		break;
	}

	return ret;
}
#endif

static int __LD_MIPI_start_stream(struct LD_MIPI *LD_MIPI)
{
	int ret;


	/* In case these controls are set before streaming */
	mutex_unlock(&LD_MIPI->mutex);
	ret = v4l2_ctrl_handler_setup(&LD_MIPI->ctrl_handler);
	mutex_lock(&LD_MIPI->mutex);


	return 0;
}

static int __LD_MIPI_stop_stream(struct LD_MIPI *LD_MIPI)
{
	return 0;
}



static int LD_MIPI_s_stream(struct v4l2_subdev *sd, int on)
{
	struct LD_MIPI *LD_MIPI = to_LD_MIPI(sd);
	struct i2c_client *client = LD_MIPI->client;
	int ret = 0;

	mutex_lock(&LD_MIPI->mutex);
	on = !!on;
	if (on == LD_MIPI->streaming)
		goto unlock_and_return;

	if (on) {
		ret = pm_runtime_get_sync(&client->dev);
		if (ret < 0) {
			pm_runtime_put_noidle(&client->dev);
			goto unlock_and_return;
		}

		ret = __LD_MIPI_start_stream(LD_MIPI);
		if (ret) {
			v4l2_err(sd, "start stream failed while write regs\n");
			pm_runtime_put(&client->dev);
			goto unlock_and_return;
		}
	} else {
		__LD_MIPI_stop_stream(LD_MIPI);
		pm_runtime_put(&client->dev);
	}

	LD_MIPI->streaming = on;

unlock_and_return:
	mutex_unlock(&LD_MIPI->mutex);

	return ret;
}

static int LD_MIPI_s_power(struct v4l2_subdev *sd, int on)
{
	struct LD_MIPI *LD_MIPI = to_LD_MIPI(sd);
	struct i2c_client *client = LD_MIPI->client;
	int ret = 0;

	mutex_lock(&LD_MIPI->mutex);

	/* If the power state is not modified - no work to do. */
	if (LD_MIPI->power_on == !!on)
		goto unlock_and_return;

	if (on) {
		ret = pm_runtime_get_sync(&client->dev);
		if (ret < 0) {
			pm_runtime_put_noidle(&client->dev);
			goto unlock_and_return;
		}
#if 0
		ret = LD_MIPI_write_array(LD_MIPI->client, LD_MIPI_global_regs);
		if (ret) {
			v4l2_err(sd, "could not set init registers\n");
			pm_runtime_put_noidle(&client->dev);
			goto unlock_and_return;
		}
#endif
		LD_MIPI->power_on = true;
	} else {
		pm_runtime_put(&client->dev);
		LD_MIPI->power_on = false;
	}

unlock_and_return:
	mutex_unlock(&LD_MIPI->mutex);

	return ret;
}

/* Calculate the delay in us by clock rate and clock cycles */
static inline u32 LD_MIPI_cal_delay(u32 cycles)
{
	return DIV_ROUND_UP(cycles, LD_MIPI_XVCLK_FREQ / 1000 / 1000);
}

static int __LD_MIPI_power_on(struct LD_MIPI *LD_MIPI)
{
	int ret;
	u32 delay_us;
	struct device *dev = &LD_MIPI->client->dev;

	if (!IS_ERR_OR_NULL(LD_MIPI->pins_default)) {
		ret = pinctrl_select_state(LD_MIPI->pinctrl,
					   LD_MIPI->pins_default);
		if (ret < 0)
			dev_err(dev, "could not set pins\n");
	}
#if 0
	ret = clk_set_rate(LD_MIPI->xvclk, LD_MIPI_XVCLK_FREQ);
	if (ret < 0) {
		dev_err(dev, "Failed to set xvclk rate (24MHz)\n");
		return ret;
	}
	if (clk_get_rate(LD_MIPI->xvclk) != LD_MIPI_XVCLK_FREQ)
		dev_warn(dev, "xvclk mismatched, modes are based on 24MHz\n");

	ret = clk_prepare_enable(LD_MIPI->xvclk);
	if (ret < 0) {
		dev_err(dev, "Failed to enable xvclk\n");
		return ret;
	}

	//if (!IS_ERR(LD_MIPI->pwr_gpio))
	//	gpiod_set_value_cansleep(LD_MIPI->pwr_gpio, 1);
	//usleep_range(500, 1000);
#endif

	if (!IS_ERR(LD_MIPI->reset_gpio))
		gpiod_set_value_cansleep(LD_MIPI->reset_gpio, 0);

	ret = regulator_bulk_enable(LD_MIPI_NUM_SUPPLIES, LD_MIPI->supplies);
	if (ret < 0) {
		dev_err(dev, "Failed to enable regulators\n");
		goto disable_clk;
	}

	if (!IS_ERR(LD_MIPI->reset_gpio))
		gpiod_set_value_cansleep(LD_MIPI->reset_gpio, 1);

	usleep_range(500, 1000);
	if (!IS_ERR(LD_MIPI->pwdn_gpio))
		gpiod_set_value_cansleep(LD_MIPI->pwdn_gpio, 1);

	/* 8192 cycles prior to first SCCB transaction */
	delay_us = LD_MIPI_cal_delay(8192);
	usleep_range(delay_us, delay_us * 2);

	return 0;

disable_clk:
	clk_disable_unprepare(LD_MIPI->xvclk);

	return ret;
}

static void __LD_MIPI_power_off(struct LD_MIPI *LD_MIPI)
{
	int ret;
	struct device *dev = &LD_MIPI->client->dev;

	if (!IS_ERR(LD_MIPI->pwdn_gpio))
		gpiod_set_value_cansleep(LD_MIPI->pwdn_gpio, 0);
	clk_disable_unprepare(LD_MIPI->xvclk);
	if (!IS_ERR(LD_MIPI->reset_gpio))
		gpiod_set_value_cansleep(LD_MIPI->reset_gpio, 0);
	if (!IS_ERR_OR_NULL(LD_MIPI->pins_sleep)) {
		ret = pinctrl_select_state(LD_MIPI->pinctrl,
					   LD_MIPI->pins_sleep);
		if (ret < 0)
			dev_dbg(dev, "could not set pins\n");
	}
	if (!IS_ERR(LD_MIPI->pwr_gpio))
		gpiod_set_value_cansleep(LD_MIPI->pwr_gpio, 0);
	regulator_bulk_disable(LD_MIPI_NUM_SUPPLIES, LD_MIPI->supplies);
}

static int LD_MIPI_runtime_resume(struct device *dev)
{
	struct i2c_client *client = to_i2c_client(dev);
	struct v4l2_subdev *sd = i2c_get_clientdata(client);
	struct LD_MIPI *LD_MIPI = to_LD_MIPI(sd);

	return __LD_MIPI_power_on(LD_MIPI);
}

static int LD_MIPI_runtime_suspend(struct device *dev)
{
	struct i2c_client *client = to_i2c_client(dev);
	struct v4l2_subdev *sd = i2c_get_clientdata(client);
	struct LD_MIPI *LD_MIPI = to_LD_MIPI(sd);

	__LD_MIPI_power_off(LD_MIPI);

	return 0;
}

#ifdef CONFIG_VIDEO_V4L2_SUBDEV_API
static int LD_MIPI_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh)
{
	struct LD_MIPI *LD_MIPI = to_LD_MIPI(sd);
	struct v4l2_mbus_framefmt *try_fmt =
				v4l2_subdev_get_try_format(sd, fh->pad, 0);
	const struct LD_MIPI_mode *def_mode = &supported_modes[0];

	mutex_lock(&LD_MIPI->mutex);
	/* Initialize try_fmt */
	try_fmt->width = def_mode->width;
	try_fmt->height = def_mode->height;
	try_fmt->code = LD_MIPI_FMT;
	try_fmt->field = V4L2_FIELD_NONE;

	mutex_unlock(&LD_MIPI->mutex);
	/* No crop or compose */

	return 0;
}
#endif


static int LD_MIPI_enum_frame_interval(struct v4l2_subdev *sd,
				       struct v4l2_subdev_pad_config *cfg,
				       struct v4l2_subdev_frame_interval_enum *fie)
{
	if (fie->index >= ARRAY_SIZE(supported_modes))
		return -EINVAL;

	if (fie->code != MEDIA_BUS_FMT_SBGGR10_1X10)
		return -EINVAL;

	fie->width = supported_modes[fie->index].width;
	fie->height = supported_modes[fie->index].height;
	fie->interval = supported_modes[fie->index].max_fps;
	return 0;
}
static int LD_MIPI_g_mbus_config(struct v4l2_subdev *sd, unsigned int pad_id,
			     struct v4l2_mbus_config *config)
{

	u32 val = 0;
	val = V4L2_MBUS_CSI2_2_LANE | V4L2_MBUS_CSI2_NONCONTINUOUS_CLOCK;
	config->type = V4L2_MBUS_CSI2_DPHY;
	config->flags = val;	
		
	return 0;
}
static const struct dev_pm_ops LD_MIPI_pm_ops = {
	SET_RUNTIME_PM_OPS(LD_MIPI_runtime_suspend,
			   LD_MIPI_runtime_resume, NULL)
};

#ifdef CONFIG_VIDEO_V4L2_SUBDEV_API
static const struct v4l2_subdev_internal_ops LD_MIPI_internal_ops = {
	.open = LD_MIPI_open,
};
#endif

static const struct v4l2_subdev_core_ops LD_MIPI_core_ops = {
	.s_power = LD_MIPI_s_power,
	.ioctl = LD_MIPI_ioctl,
#ifdef CONFIG_COMPAT
	.compat_ioctl32 = LD_MIPI_compat_ioctl32,
#endif
};

static const struct v4l2_subdev_video_ops LD_MIPI_video_ops = {
	.s_stream = LD_MIPI_s_stream,
	.g_frame_interval = LD_MIPI_g_frame_interval,
};

static const struct v4l2_subdev_pad_ops LD_MIPI_pad_ops = {
	.enum_mbus_code = LD_MIPI_enum_mbus_code,
	.enum_frame_size = LD_MIPI_enum_frame_sizes,
	.enum_frame_interval = LD_MIPI_enum_frame_interval,
	.get_fmt = LD_MIPI_get_fmt,
	.set_fmt = LD_MIPI_set_fmt,
	.get_mbus_config = LD_MIPI_g_mbus_config,
};

static const struct v4l2_subdev_ops LD_MIPI_subdev_ops = {
	.core	= &LD_MIPI_core_ops,
	.video	= &LD_MIPI_video_ops,
	.pad	= &LD_MIPI_pad_ops,
};

static int LD_MIPI_set_ctrl(struct v4l2_ctrl *ctrl)
{
	struct LD_MIPI *LD_MIPI = container_of(ctrl->handler,
					     struct LD_MIPI, ctrl_handler);

	struct i2c_client *client = LD_MIPI->client;
	s64 max;
	int ret = 0;

	/* Propagate change of current control to all related controls */
	switch (ctrl->id) {
	case V4L2_CID_VBLANK:
		/* Update max exposure while meeting expected vblanking */
		max = LD_MIPI->cur_mode->height + ctrl->val - 4;
		__v4l2_ctrl_modify_range(LD_MIPI->exposure,
					 LD_MIPI->exposure->minimum, max,
					 LD_MIPI->exposure->step,
					 LD_MIPI->exposure->default_value);
		break;
	}

	if (pm_runtime_get(&client->dev) <= 0)
		return 0;

	switch (ctrl->id) {
	case V4L2_CID_EXPOSURE:
		/* 4 least significant bits of expsoure are fractional part */
		ret = 0;
		break;
	case V4L2_CID_ANALOGUE_GAIN:
		ret = 0;
		break;
	case V4L2_CID_VBLANK:
		ret = 0;
		break;
	case V4L2_CID_TEST_PATTERN:
		ret = LD_MIPI_enable_test_pattern(LD_MIPI, ctrl->val);
		break;
	default:
		dev_warn(&client->dev, "%s Unhandled id:0x%x, val:0x%x\n",
			 __func__, ctrl->id, ctrl->val);
		break;
	}

	pm_runtime_put(&client->dev);

	return ret;

}

static const struct v4l2_ctrl_ops LD_MIPI_ctrl_ops = {
	.s_ctrl = LD_MIPI_set_ctrl,
};

static int LD_MIPI_initialize_controls(struct LD_MIPI *LD_MIPI)
{
	const struct LD_MIPI_mode *mode;
	struct v4l2_ctrl_handler *handler;
	struct v4l2_ctrl *ctrl;
	s64 exposure_max, vblank_def;
	u32 h_blank;
	int ret;

	handler = &LD_MIPI->ctrl_handler;
	mode = LD_MIPI->cur_mode;
	ret = v4l2_ctrl_handler_init(handler, 8);
	if (ret)
		return ret;
	handler->lock = &LD_MIPI->mutex;

	ctrl = v4l2_ctrl_new_int_menu(handler, NULL, V4L2_CID_LINK_FREQ,
				      0, 0, link_freq_menu_items);
	if (ctrl)
		ctrl->flags |= V4L2_CTRL_FLAG_READ_ONLY;

	v4l2_ctrl_new_std(handler, NULL, V4L2_CID_PIXEL_RATE,
			  0, LD_MIPI_PIXEL_RATE, 1, LD_MIPI_PIXEL_RATE);

	h_blank = mode->hts_def - mode->width;
	LD_MIPI->hblank = v4l2_ctrl_new_std(handler, NULL, V4L2_CID_HBLANK,
				h_blank, h_blank, 1, h_blank);
	if (LD_MIPI->hblank)
		LD_MIPI->hblank->flags |= V4L2_CTRL_FLAG_READ_ONLY;

	vblank_def = mode->vts_def - mode->height;
	LD_MIPI->vblank = v4l2_ctrl_new_std(handler, &LD_MIPI_ctrl_ops,
				V4L2_CID_VBLANK, vblank_def,
				LD_MIPI_VTS_MAX - mode->height,
				1, vblank_def);

	exposure_max = mode->vts_def - 4;
	LD_MIPI->exposure = v4l2_ctrl_new_std(handler, &LD_MIPI_ctrl_ops,
				V4L2_CID_EXPOSURE, LD_MIPI_EXPOSURE_MIN,
				exposure_max, LD_MIPI_EXPOSURE_STEP,
				mode->exp_def);

	LD_MIPI->anal_gain = v4l2_ctrl_new_std(handler, &LD_MIPI_ctrl_ops,
				V4L2_CID_ANALOGUE_GAIN, LD_MIPI_GAIN_MIN,
				LD_MIPI_GAIN_MAX, LD_MIPI_GAIN_STEP,
				LD_MIPI_GAIN_DEFAULT);

	LD_MIPI->test_pattern = v4l2_ctrl_new_std_menu_items(handler,
				&LD_MIPI_ctrl_ops, V4L2_CID_TEST_PATTERN,
				ARRAY_SIZE(LD_MIPI_test_pattern_menu) - 1,
				0, 0, LD_MIPI_test_pattern_menu);

	if (handler->error) {
		ret = handler->error;
		dev_err(&LD_MIPI->client->dev,
			"Failed to init controls(%d)\n", ret);
		goto err_free_handler;
	}

	LD_MIPI->subdev.ctrl_handler = handler;

	return 0;

err_free_handler:
	v4l2_ctrl_handler_free(handler);

	return ret;
}

static int LD_MIPI_check_sensor_id(struct LD_MIPI *LD_MIPI,
				   struct i2c_client *client)
{
	struct device *dev = &LD_MIPI->client->dev;
	u32 id = 0;

	dev_info(dev, "LIDE MIPI REVISION 0x%x\n",  id);

	return 0;
}

static int LD_MIPI_configure_regulators(struct LD_MIPI *LD_MIPI)
{
	unsigned int i;

	for (i = 0; i < LD_MIPI_NUM_SUPPLIES; i++)
		LD_MIPI->supplies[i].supply = LD_MIPI_supply_names[i];

	return devm_regulator_bulk_get(&LD_MIPI->client->dev,
				       LD_MIPI_NUM_SUPPLIES,
				       LD_MIPI->supplies);
}

static int LD_MIPI_probe(struct i2c_client *client,
			 const struct i2c_device_id *id)
{
	struct device *dev = &client->dev;
	struct device_node *node = dev->of_node;
	struct LD_MIPI *LD_MIPI;
	struct v4l2_subdev *sd;
	char facing[2];
	int ret;

	dev_info(dev, "driver version: %02x.%02x.%02x",
		DRIVER_VERSION >> 16,
		(DRIVER_VERSION & 0xff00) >> 8,
		DRIVER_VERSION & 0x00ff);

	LD_MIPI = devm_kzalloc(dev, sizeof(*LD_MIPI), GFP_KERNEL);
	if (!LD_MIPI)
		return -ENOMEM;

	ret = of_property_read_u32(node, RKMODULE_CAMERA_MODULE_INDEX,
				   &LD_MIPI->module_index);
	ret |= of_property_read_string(node, RKMODULE_CAMERA_MODULE_FACING,
				       &LD_MIPI->module_facing);
	ret |= of_property_read_string(node, RKMODULE_CAMERA_MODULE_NAME,
				       &LD_MIPI->module_name);
	ret |= of_property_read_string(node, RKMODULE_CAMERA_LENS_NAME,
				       &LD_MIPI->len_name);
	if (ret) {
		dev_err(dev, "could not get module information!\n");
		return -EINVAL;
	}

	LD_MIPI->client = client;
	LD_MIPI->cur_mode = &supported_modes[0];

	// LD_MIPI->xvclk = devm_clk_get(dev, "xvclk");
	// if (IS_ERR(LD_MIPI->xvclk)) {
		// dev_err(dev, "Failed to get xvclk\n");
		// return -EINVAL;
	// }
	

	LD_MIPI->pwr_gpio = devm_gpiod_get(dev, "power", GPIOD_OUT_LOW);
	if (IS_ERR(LD_MIPI->pwr_gpio))
		dev_warn(dev, "Failed to get pwr-gpios\n");

	LD_MIPI->reset_gpio = devm_gpiod_get(dev, "reset", GPIOD_OUT_LOW);
	if (IS_ERR(LD_MIPI->reset_gpio))
		dev_warn(dev, "Failed to get reset-gpios\n");

	LD_MIPI->pwdn_gpio = devm_gpiod_get(dev, "pwdn", GPIOD_OUT_LOW);
	if (IS_ERR(LD_MIPI->pwdn_gpio))
		dev_warn(dev, "Failed to get pwdn-gpios\n");

	ret = LD_MIPI_configure_regulators(LD_MIPI);
	if (ret) {
		dev_err(dev, "Failed to get power regulators\n");
		return ret;
	}

	LD_MIPI->pinctrl = devm_pinctrl_get(dev);
	if (!IS_ERR(LD_MIPI->pinctrl)) {
		LD_MIPI->pins_default =
			pinctrl_lookup_state(LD_MIPI->pinctrl,
					     OF_CAMERA_PINCTRL_STATE_DEFAULT);
		if (IS_ERR(LD_MIPI->pins_default))
			dev_err(dev, "could not get default pinstate\n");

		LD_MIPI->pins_sleep =
			pinctrl_lookup_state(LD_MIPI->pinctrl,
					     OF_CAMERA_PINCTRL_STATE_SLEEP);
		if (IS_ERR(LD_MIPI->pins_sleep))
			dev_err(dev, "could not get sleep pinstate\n");
	}

	mutex_init(&LD_MIPI->mutex);

	sd = &LD_MIPI->subdev;
	v4l2_i2c_subdev_init(sd, client, &LD_MIPI_subdev_ops);
	ret = LD_MIPI_initialize_controls(LD_MIPI);
	if (ret)
		goto err_destroy_mutex;

	ret = __LD_MIPI_power_on(LD_MIPI);
	if (ret)
		goto err_free_handler;

	ret = LD_MIPI_check_sensor_id(LD_MIPI, client);
	if (ret)
		goto err_power_off;

#ifdef CONFIG_VIDEO_V4L2_SUBDEV_API
	sd->internal_ops = &LD_MIPI_internal_ops;
	sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE;
#endif
#if defined(CONFIG_MEDIA_CONTROLLER)
	LD_MIPI->pad.flags = MEDIA_PAD_FL_SOURCE;
	sd->entity.function = MEDIA_ENT_F_CAM_SENSOR;
	ret = media_entity_pads_init(&sd->entity, 1, &LD_MIPI->pad);
	if (ret < 0)
		goto err_power_off;
#endif

	memset(facing, 0, sizeof(facing));
	if (strcmp(LD_MIPI->module_facing, "back") == 0)
		facing[0] = 'b';
	else
		facing[0] = 'f';

	snprintf(sd->name, sizeof(sd->name), "m%02d_%s_%s %s",
		 LD_MIPI->module_index, facing,
		 LD_MIPI_NAME, dev_name(sd->dev));
	ret = v4l2_async_register_subdev_sensor_common(sd);
	if (ret) {
		dev_err(dev, "v4l2 async register subdev failed\n");
		goto err_clean_entity;
	}

	pm_runtime_set_active(dev);
	pm_runtime_enable(dev);
	pm_runtime_idle(dev);

	printk("sdi LD_MIPI probe end\n");

	return 0;

err_clean_entity:
#if defined(CONFIG_MEDIA_CONTROLLER)
	media_entity_cleanup(&sd->entity);
#endif
err_power_off:
	__LD_MIPI_power_off(LD_MIPI);
err_free_handler:
	v4l2_ctrl_handler_free(&LD_MIPI->ctrl_handler);
err_destroy_mutex:
	mutex_destroy(&LD_MIPI->mutex);

	return ret;
}

static int LD_MIPI_remove(struct i2c_client *client)
{
	struct v4l2_subdev *sd = i2c_get_clientdata(client);
	struct LD_MIPI *LD_MIPI = to_LD_MIPI(sd);

	v4l2_async_unregister_subdev(sd);
#if defined(CONFIG_MEDIA_CONTROLLER)
	media_entity_cleanup(&sd->entity);
#endif
	v4l2_ctrl_handler_free(&LD_MIPI->ctrl_handler);
	mutex_destroy(&LD_MIPI->mutex);

	pm_runtime_disable(&client->dev);
	if (!pm_runtime_status_suspended(&client->dev))
		__LD_MIPI_power_off(LD_MIPI);
	pm_runtime_set_suspended(&client->dev);

	return 0;
}

#if IS_ENABLED(CONFIG_OF)
static const struct of_device_id LD_MIPI_of_match[] = {
	{ .compatible = "mine,sdi_to_mipi" },
	{},
};
MODULE_DEVICE_TABLE(of, LD_MIPI_of_match);
#endif

static const struct i2c_device_id LD_MIPI_match_id[] = {
	{ "ovti,LD_MIPI", 0 },
	{ },
};

static struct i2c_driver LD_MIPI_i2c_driver = {
	.driver = {
		.name = LD_MIPI_NAME,
		.pm = &LD_MIPI_pm_ops,
		.of_match_table = of_match_ptr(LD_MIPI_of_match),
	},
	.probe		= &LD_MIPI_probe,
	.remove		= &LD_MIPI_remove,
	.id_table	= LD_MIPI_match_id,
};

static int __init sensor_mod_init(void)
{
	return i2c_add_driver(&LD_MIPI_i2c_driver);
}

static void __exit sensor_mod_exit(void)
{
	i2c_del_driver(&LD_MIPI_i2c_driver);
}

device_initcall_sync(sensor_mod_init);
module_exit(sensor_mod_exit);

MODULE_DESCRIPTION("OmniVision LD_MIPI sensor driver");
MODULE_LICENSE("GPL v2");
